<template>
  <div class="app-container">
    <form-filter @on-filter="submitFilterForm" />
    <el-button type="primary" class="mgtop" @click="openDialog" v-if="roleCheck('data-add')">添加</el-button>
    <el-button type="primary" @click="dialogVisible=true" v-if="roleCheck('add-upload')">数据上传</el-button>
    <el-button type="primary" @click="batchDelete">批量删除</el-button>
    <el-table border :data="tableData.list"
              v-loading="loading"
              @selection-change="handleSelectionChange"
              element-loading-text="加载中..."   >
      <el-table-column type="selection"></el-table-column>
      <el-table-column label="数据补录开始时间"  prop="startTime" align="center"  >
        <template slot-scope="{row}">{{row.startTime | toTime('YYYY-MM-DD HH:mm:ss')}}</template>
      </el-table-column>
      <el-table-column label="数据补录结束时间"  prop="endTime" align="center"  >
        <template slot-scope="{row}">{{row.endTime | toTime('YYYY-MM-DD HH:mm:ss')}}</template>
      </el-table-column>
      <el-table-column label="任务执行开始时间"  prop="jobStartTime" align="center"  >
        <template slot-scope="{row}">{{row.jobStartTime | toTime('YYYY-MM-DD HH:mm:ss')}}</template>
      </el-table-column>
      <el-table-column label="任务执行结束时间"  prop="jobEndTime" align="center"  >
        <template slot-scope="{row}">{{row.jobEndTime | toTime('YYYY-MM-DD HH:mm:ss')}}</template>
      </el-table-column>
      <el-table-column label="渠道"  prop="channelId" align="center" ></el-table-column>
      <el-table-column label="类型"  prop="dataType" align="center" >
        <template slot-scope="{row}">{{row.dataType|toConverter(DATA_TYPE_LIST)}}</template>
      </el-table-column>
      <el-table-column label="补录人"  prop="createUser" align="center" >
      </el-table-column>
      <el-table-column label="文件目录"  prop="fileFolder" align="center" >
      </el-table-column>
      <el-table-column label="文件名"  prop="fileName" align="center" >
      </el-table-column>
      <el-table-column label="数据量"  prop="recordCount" align="center" >
      </el-table-column>
      <el-table-column label="状态"  prop="status" align="center" >
      </el-table-column>
      <el-table-column label="备注"  prop="remark" align="center" >
      </el-table-column>

    </el-table>

    <div class="pagination-container">
      <el-pagination background @size-change="gridSizeChange" @current-change="gridCurrentChange"
                     :current-page="filters.page" :page-sizes="gridPageSize" :page-size="filters.size"
                     :layout="gridLayout" :total="Number(tableData.total)">
      </el-pagination>
    </div>
     <AddDialog
      :dialogVisible="addDialogVisible"
      v-if="addDialogVisible"
      @cancel="addDialogVisible = false"
    />
    <!--上传数据-->
    <el-dialog
     title="上传"
     width="600px"
    :show-close="false"
     custom-class="upload_data"
     :visible="dialogVisible"
     >
     <el-form
     ref="refForm"
    :rules="refRule"
    :disabled="loading"
     label-width="100px"
    :model="form" class="demo-form-inline">

         <el-form-item label="游戏平台" prop="gamePlatformId" width="300px" >
            <el-select v-model="form.gamePlatformId " >
              <el-option
                v-for="item in GAME_PLATFORM_LIST.filter((item)=>{return item.type.includes('dataAddRecord')})"
                :label="item.title"
                :key="item.value"
                :value="item.value"
                :multiple="true"
              ></el-option>
            </el-select>
        </el-form-item>
         <el-form-item label="字符集" prop="charsetName" width="300px" >
            <el-select v-model="form.charsetName " >
              <el-option label="GBK" value="GBK"></el-option>
              <el-option label="UTF-8" value="UTF-8"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item prop="fileS" label="文件">
          <el-upload
          :multiple="true"
          class="upload-demo"
          ref="upload"
          action="/api/gl/xjLivejob/upload"
          :on-change="handleSuccess"
          :on-success="successFn"
          :on-error="errorFn"
          :headers="header"
          :data="form"
          :file-list="fileList"
          :auto-upload="false">
          <el-button slot="trigger" size="small" type="primary" icon='el-icon-upload'>选取文件</el-button>
        </el-upload>
        </el-form-item>
     </el-form>

       <div  style="text-align:right;width:100%;margin-top:10px">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="toUpload">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import md5 from 'blueimp-md5';
import FormFilter from './dataAddRecordFilter.vue';
import AddDialog from './dialog/addDataRecordDialog.vue';
import { grid, form } from '@/build';
import { getLogin } from '@/utils/auth';
import { manualjobsList, batchDeleteManualjobs } from '@/services/api/gameDataManage';
import {
  GAME_PLATFORM_LIST, DATA_TYPE_LIST,
} from './data';

export default {
  name: 'tab-one',
  mixins: [grid, form],
  components: {
    FormFilter,
    AddDialog,
    // EditorApp,
  },

  data() {
    return {
      url: consts.MANUAL_JOBS_LIST_ADD,
      fileList: [],
      istap: true,
      GAME_PLATFORM_LIST,
      dialogVisible: false,
      DATA_TYPE_LIST,
      addDialogVisible: false,
      tableData: {
        list: [],
        total: 0,
      },
      form: {
        gamePlatformId: null,
        fileS: [],
        charsetName: '',
      },
      refRule: {
        fileS: [
          { required: true, message: '文件不能为空', trigger: 'change' },
        ],
        gamePlatformId: [
          { required: true, message: '游戏平台为必选项', trigger: 'change' },
        ],
      },
      filters: {
        gamePlatform: null,
        status: null,
        dataType: null,
        page: 1,
        size: 20,
        startTime: moment().format('YYYY-MM-DD 00:00:00'),
        endTime: moment().format('YYYY-MM-DD 23:59:59'),
        jobStartTime: null,
        jobEndTime: null,
      },
      selectedItem: [],
    };
  },
  computed: {
    header() {
      return this._addSign();
    },
  },
  methods: {
    batchDelete() { // 批量删除
      this.$confirm('您确定要删除选中项吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      })
        .then(() => {
          this.doSave({ action: 'batchDelete' });
        }).catch(() => {});
    },
    handleSelectionChange(val) {
      this.selectedItem = val;
    },
    _addSign() {
      const timestamp = Date.parse(new Date());
      const signParams = {};
      const { token, uid } = getLogin();
      signParams.device_id = '1.0';
      signParams.os_type = 0;
      signParams.timestamp = timestamp;
      signParams.version = '1.0';
      const urlStr = this.urlEncode(signParams).substr(1);
      signParams.token = token;
      signParams.uid = uid;
      signParams.sign = md5(`${urlStr}global`);
      // console.log(urlStr)

      return signParams;
    },
    urlEncode(param, key, encode) {
      if (param == null) return '';
      let paramStr = '';
      const t = typeof (param);
      if (t == 'string' || t == 'number' || t == 'boolean') {
        paramStr += `&${key}=${(encode == null || encode) ? encodeURIComponent(param) : param}`;
      } else {
        for (const i in param) {
          const k = key == null ? i : key + (param instanceof Array ? `[${i}]` : `.${i}`);
          paramStr += this.urlEncode(param[i], k, encode);
        }
      }
      return paramStr;
    },
    successFn() {
      this.dialogVisible = false;
      this.$message({
        type: 'success',
        message: '上传成功',
      });
    },
    errorFn(err, file, fileList) {
      this.dialogVisible = false;
      this.$message({
        type: 'error',
        message: err,
      });
    },
    handleSuccess(file, fileList) {
      this.form.fileS = fileList;
    },
    openDialog() {
      this.addDialogVisible = true;
      window.scrollTo(0, 0);
    },
    submitFilterForm(formInline) {
      const { time } = formInline;
      if (!_.isUndefined(time) && _.isArray(time)) {
        this.filters.startTime = time[0];
        this.filters.endTime = time[1];
      } else {
        this.filters.startTime = undefined;
        this.filters.endTime = undefined;
      }
      this.filters.jobStartTime = !formInline.jobTime ? undefined : formInline.jobTime[0];
      this.filters.jobEndTime = !formInline.jobTime ? undefined : formInline.jobTime[1];
      this.filters = { ...this.filters, ...formInline };
      this.doGet({ action: 'getGrid' });
    },
    toUpload() {
      this.$refs.refForm.validate((valid) => {
        if (valid) {
          this.$refs.upload.submit();
          this.dialogVisible = false;
        } else {
          return false;
        }
      });
    },
  },
  mounted() {
    this.bindGet(manualjobsList, 'tableData', {
      action: 'getGrid',
      sendingData: 'filters',
      beforeSend: (data) => {
        delete data.time;
        return data;
      },
    });
    this.getAll();
    this.bindSave(batchDeleteManualjobs, 'batchDelete', '', {
      beforeSend: () => {
        const idArr = this.selectedItem.map(item => item.rid).join(',');
        return {
          idList: idArr,
        };
      },
      callback: ([result, data]) => {
        if (result) {
          this.doGet({ action: 'getGrid' });
          this.$notify({
            title: '删除成功',
            type: 'success',
            duration: 2000,
          });
        } else {
          this.$notify({
            title: `删除失败.${data && data.message}`,
            type: 'error',
            duration: 2000,
          });
        }
      },
    });
  },
};
</script>
<style scope lang="scss">
  .mgtop{
    margin-top:30px;
    margin-bottom: 10px;
  }
  /deep/ {
    .upload_data{
      .el-form-item{
        .el-form-item__content{
          width:calc(90% - 150px);
          .el-select{
            width: 100%;
          }
          .el-date-editor{
            width:100%;
          }
        }
      }
    }
  }
</style>
